package com.jcsz.sso.server.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @className: LoginController
 * @author: 一把Po吉他
 * @date: 2022/11/9 20:44
 * @version: 1.0
 **/
@Controller
public class LoginController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping("/userInfo")
    @ResponseBody
    public String userInfo(@RequestParam("token") String token) {
        String username = redisTemplate.opsForValue().get(token);
        return username;
    }

    @GetMapping("/login.html")
    public String hello(@RequestParam(value = "redirect_url") String url, @CookieValue(value = "SSO_TOKEN", required = false) String sso_token, Model model) {

        if (!StringUtils.isEmpty(sso_token)) {
            return "redirect:" + url + "?token=" + sso_token;
        }

        model.addAttribute("url", url);
        return "login";
    }

    @PostMapping("/doLogin")
    public String doLogin(@RequestParam("redirect_url") String redirect_url, String username, String password, HttpServletResponse response) {
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            String uuid = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(uuid, username);
            response.addCookie(new Cookie("SSO_TOKEN", uuid));
            return "redirect:" + redirect_url + "?token=" + uuid;
        }
        return "login";
    }
}
